package com.jfeat.am.module.wegou.aop;

import com.jfeat.am.common.constant.tips.ErrorTip;
import com.jfeat.am.common.exception.BusinessException;
import com.jfeat.am.core.shiro.ShiroKit;
import com.jfeat.am.core.shiro.ShiroUser;
import com.jfeat.am.core.support.HttpKit;
import com.jfeat.am.core.support.StrKit;
import com.jfeat.am.module.wegou.annotation.UserIdentity;
import com.jfeat.am.module.wegou.constant.IdentityEnum;
import com.jfeat.am.module.wegou.exception.WegouBizException;
import com.jfeat.am.module.wegou.services.crud.service.ProductStoreService;
import com.jfeat.am.module.wegou.services.patch.UserIdentityPatchService;
import com.jfeat.am.module.wegou.services.persistence.model.ProductStore;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * Created by Administrator on 2018/2/6.
 */
@Aspect
@Component
public class UserIdentityAop {
    @Resource
    UserIdentityPatchService userIdentityPatchService;
    @Resource
    ProductStoreService productStoreService;

    private Logger log = Logger.getLogger(this.getClass());

    @Pointcut(value = "@annotation(com.jfeat.am.module.wegou.annotation.UserIdentity)")
    public void cutService() {
    }

    /**
     * 校验身份
     */
    @Around("cutService()")
    public Object verify(ProceedingJoinPoint point) throws Throwable {

        try {
            handle(point);
        } catch (BusinessException e) {
            log.error("校验出错!", e);
            return ErrorTip.create(e.getCode(), e.getMessage());
        }

        //执行业务
        Object result = point.proceed();
        return result;
    }

    private void handle(ProceedingJoinPoint point) throws Exception {
        //获取拦截的方法名
        Signature sig = point.getSignature();
        MethodSignature msig = null;
        if (!(sig instanceof MethodSignature)) {
            throw new IllegalArgumentException("该注解只能用于方法");
        }
        msig = (MethodSignature) sig;

        Object target = point.getTarget();
        Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());

        //如果当前用户未登录
        ShiroUser user = ShiroKit.getUser();
        if (null == user) {
            throw new BusinessException(401, "请登录再进行此操作");
        }

        //获取操作名称
        UserIdentity annotation = currentMethod.getAnnotation(UserIdentity.class);
        String identity = annotation.value(); // identify ="STORE"
        if (IdentityEnum.PLATFORM.toString().equals(identity) || StrKit.isBlank(identity)) {
            if (!userIdentityPatchService.isIdentity(user.getId(), IdentityEnum.PLATFORM.toString())) {
                throw new BusinessException(WegouBizException.NOT_ADMIN.getCode(),
                        WegouBizException.NOT_ADMIN.getMessage());
            }
        } else if (IdentityEnum.STORE.toString().equals(identity)) {
            if (!(userIdentityPatchService.isIdentity(user.getId(), IdentityEnum.RESTAURANT.toString())
                    || userIdentityPatchService.isIdentity(user.getId(), IdentityEnum.CANTEEN.toString()))) {
                throw new BusinessException(WegouBizException.NOT_RESTAURANT_OR_CANTEEN.getCode(),
                        WegouBizException.NOT_RESTAURANT_OR_CANTEEN.getMessage());
            }
            ProductStore productStore = productStoreService.findFirstByUserId(user.getId());  //一个用户只能有一家料理店铺
            if (productStore == null) {
                throw new BusinessException(WegouBizException.NOT_RESTAURANT_OR_CANTEEN.getCode(),
                        WegouBizException.NOT_RESTAURANT_OR_CANTEEN.getMessage());
            }
            if (productStore.getLocked().equals(1)) {
                throw new BusinessException(WegouBizException.SHOP_LOCKED.getCode(),
                        WegouBizException.SHOP_LOCKED.getMessage());
            }
            HttpServletRequest httpServletRequest = HttpKit.getRequest();
            httpServletRequest.setAttribute("productStore", productStore);
        }else {
            throw new BusinessException(WegouBizException.UNKNOWN_IDENTITY.getCode(),
                    WegouBizException.UNKNOWN_IDENTITY.getMessage());
        }
    }
}
